#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Using: GPLv3
#Author: stuyorks@gmail.com

import urllib2
import urllib
import re
import sys

class CREDIT(object):
    def __init__(self):
        pass

    def login(self, account, passwd):
        """
          login function: To login CREDIT.STU.EDU.CN, and get Cookies

               first, Get LoginPage to get the cookiesASP
               then POST to login to get .credit Cookies
               
               return: cookiesASP+'; '+.creditCookies
                     
        """
        loginURL = 'http://credit.stu.edu.cn/Portal/STULogin.aspx'

        headers = { 'Accept':'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*',
                    'Accept-Language':'zh-cn',
                    'User-agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5',
                    'Host':'credit.stu.edu.cn',
                    'Connection':'keep-alive',
                  }

        req = urllib2.Request(loginURL)
        res = urllib2.urlopen(req)
        head = str(res.info())
        #print head
        cookieASP = re.findall(r"Set-Cookie:\s+(.+?);", head, re.M)[0]

        #print cookieASP
        #print res.read().decode('gbk').encode('utf-8')
       
        body="""__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUKLTIzOTI5NzAzOGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFCGJ0bkxvZ2luhgJWmLv3o32M3tTFy19drwb57dQ%3D"""+"""&txtUserID=%s&txtUserPwd=%s"""% (account, passwd)+"""&__EVENTVALIDATION=%2FwEWBALPsY6aCQLT8dy8BQLG8eCkDwKC3IeGDCar7PvQsA7DUEdMVBiO9kxmfwdP&btnLogin.x=0&btnLogin.y=0"""
        
        headers = { 'Accept':'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*',
                    'Referer':'http://credit.stu.edu.cn/Portal/STULogin.aspx',
                    'Accept-Language':'zh-cn',
                    'Content-Type':'application/x-www-form-urlencoded',
                    'Accept-Encoding':'gzip, deflate',
                    'User-agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5',
                    'Host':'credit.stu.edu.cn',
                    'Content-Length':'%s' % len(body),
                    'Connection':'Keep-Alive',
                    'Cache-Control':'no-cache',
                    'Cookie':'%s' % cookieASP
                  }
        #print body
        req = urllib2.Request(loginURL, headers=headers, data=body)
        res = urllib2.urlopen(req)
        head = str(res.info())
        #print head
        #page = res.read().decode('gbk').encode('utf-8')
        cookieCredit = re.findall(r"Set-Cookie:\s+(.+?);", head, re.M)[0]
        cookie = cookieASP+"; "+cookieCredit
        return cookie


    def selectCourse(self, courseID, cookie):
        """
          selectCourse funtion: To slect a courese by its ID.
                 courseID: the course id to be selected.
                 cookie: the login function returen 
                 
                 return: The Message of response page
        """
        headers = { 'Accept':'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*',
                    'Referer':'http://credit.stu.edu.cn/Modules/SelectFrame.aspx?url=../Elective/ElectCourse.aspx?CourseID=%s$jc_flg=1'% courseID,
                    'Accept-Language':'zh-cn',
                    'Content-Type':'application/x-www-form-urlencoded',
                    'Accept-Encoding':'gzip, deflate',
                    'User-agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5',
                    'Host':'credit.stu.edu.cn',
                    'Connection':'Keep-Alive',
                    'Cache-Control':'no-cache',
                    'Cookie':'%s' % cookie
                  }
        #print body
        slectURL="http://credit.stu.edu.cn/Elective/ElectCourse.aspx?CourseID=%s&jc_flg=1"% courseID
        req = urllib2.Request(slectURL, headers=headers)
        res = urllib2.urlopen(req)
        head = str(res.info())
        #print head
        page = res.read().decode('gbk').encode('utf-8')
        resMsg=page.split('<span id="lbl_msg">')[1].split('</span></TD>')[0].strip()
        return resMsg
        #print resMsg
        #print page
      
    def getCourseList(self,cookie):
        """
          getCourseList funtion: To get the courseList which have selected!
                 cookie: the login function returen 
                 
                 return: 
                         viewstate: 
                         EVENTVALIDATION:
                         cbo_xnxq: The semester
                         courseList: (courseID,listIndex)
        """
        headers = { 'Accept':'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*',
                    'Referer':'http://credit.stu.edu.cn/Elective/MyElectiveList.aspx',
                    'Accept-Language':'zh-cn',
                    'Content-Type':'application/x-www-form-urlencoded',
                    'Accept-Encoding':'gzip, deflate',
                    'User-agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5',
                    'Host':'credit.stu.edu.cn',
                    'Connection':'Keep-Alive',
                    'Cache-Control':'no-cache',
                    'Cookie':'%s' % cookie
                  }

        myElectiveListURL="http://credit.stu.edu.cn/Elective/MyElectiveList.aspx"
        req = urllib2.Request(myElectiveListURL, headers=headers)
        res = urllib2.urlopen(req)
        head = str(res.info())
        page = res.read().decode('gbk').encode('utf-8')

        viewstate=page.split('<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"')[1].split('/>')[0].strip().replace('value="','').replace('"','')
        EVENTVALIDATION=page.split('<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="')[1].split('/>')[0].strip().replace('"','')
        cbo_xnxq = page.split('<option selected="selected" value="')[1].split('">')[0]

        courseNum=page.count('您确实要删除该行')#Calc how many courses.
        courseList= []
        for i in range(0, courseNum):
            courseList.append((page.split('<a id="dgd_Course_ctl0%s_HyperLink1"'% str(i+2))[1][104:109], i+2))

        return viewstate, EVENTVALIDATION, cbo_xnxq, courseList
    
    def delCourse(self, courseID, listNum, cbo_xnxq, cookie, viewState, EVENTVALIDATION):
        """
          delCourse funtion: To del a course by listNum which from the getCourseList function.
                 courseID: the course id to be deleted.
                 listNum:  the index of courese to be deleted
                 cbo_xnxq: semester which from the getCourseList function
                 cookie: the login function returen 
                 viewState:  from the getCourseList function
                 EVENTVALIDATION: from the getCourseList function
                 
                 return: True. if cannot find the deleted's courseID string.
        """
        headers = { 'Accept':'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*',
                    'Referer':'http://credit.stu.edu.cn/Elective/MyElectiveList.aspx',
                    'Accept-Language':'zh-cn',
                    'Content-Type':'application/x-www-form-urlencoded',
                    'Accept-Encoding':'gzip, deflate',
                    'User-agent':'Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5',
                    'Host':'credit.stu.edu.cn',
                    'Connection':'Keep-Alive',
                    'Cache-Control':'no-cache',
                    'Cookie':'%s' % cookie
                  }
        
        body=[('__EVENTTARGET',''),('__EVENTARGUMENT',''),('__LASTFOCUS',''),
              ('__VIEWSTATE','%s'% viewState),('cbo_xnxq','%s'% cbo_xnxq),
              ('__EVENTVALIDATION','%s'% EVENTVALIDATION),
              ('dgd_Course$ctl0%s$clm_Del.x'% listNum,'8'),
              ('dgd_Course$ctl0%s$clm_Del.y'% listNum,'5')
             ]

        myElectiveListURL="http://credit.stu.edu.cn/Elective/MyElectiveList.aspx"
        req = urllib2.Request(myElectiveListURL, headers=headers, data=urllib.urlencode(body))
        res = urllib2.urlopen(req)
        head = str(res.info())
        #print head
        page = res.read().decode('gbk').encode('utf-8')
        #print page
        if page.find('target="_blank">%s</a>'% courseID) == -1:#can not find the string means that the course has deleted!
            return True

def main():

    account = raw_input("Input account:")
    password = raw_input("password:")
    courseID= raw_input("courseID want to select or deleted:")
    credit=CREDIT()

    cookie = credit.login(account, password)
    while cookie:
        #viewState, EVENTVALIDATION, cbo_xnxq, courseList = credit.getCourseList(cookie)
        #for course in courseList:
            #if courseID in course:
                #listNum=course[1]
                #isDel = credit.delCourse(courseID, listNum, cbo_xnxq, cookie, viewState, EVENTVALIDATION)
                #if isDel:
                    #print "course:%s deleted!"% courseID
                    #break
                #else:
                    #print "ERROR..delete"
                    #break
            
        #sys.exit(0)
        #resultMsg = credit.selectCourse(courseID, cookie)
        #if resultMsg.find('是否订购教材') != -1:
            #print "%s课程已经选中!" % courseID
            #sys.exit(0)
        #else:
            #sleep(1) # 1秒

if __name__ == "__main__":
    main()
